package com.shuda.business.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.channel.dto.DistributionSchemeDTO;
import com.shuda.business.channel.dto.DistributionSchemeQueryDTO;
import com.shuda.business.channel.entity.DistributionSchemeEntity;
import com.shuda.business.channel.mapper.DistributionSchemeMapper;
import com.shuda.business.channel.service.DistributionSchemeService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.dto.PageResult;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分发方案服务实现类
 */
@Service
public class DistributionSchemeServiceImpl extends ServiceImpl<DistributionSchemeMapper, DistributionSchemeEntity> 
        implements DistributionSchemeService {

    @Autowired
    private DistributionSchemeMapper distributionSchemeMapper;

    @Override
    public PageResult<DistributionSchemeDTO> getDistributionSchemePage(PageDTO pageDTO, DistributionSchemeQueryDTO queryDTO) {
        Page<DistributionSchemeEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        LambdaQueryWrapper<DistributionSchemeEntity> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getSchemeName())) {
            wrapper.like(DistributionSchemeEntity::getSchemeName, queryDTO.getSchemeName());
        }
        
        if (StringUtils.hasText(queryDTO.getSchemeCode())) {
            wrapper.eq(DistributionSchemeEntity::getSchemeCode, queryDTO.getSchemeCode());
        }
        
        if (queryDTO.getUpstreamChannelId() != null) {
            wrapper.eq(DistributionSchemeEntity::getUpstreamChannelId, queryDTO.getUpstreamChannelId());
        }
        
        if (queryDTO.getDownstreamChannelId() != null) {
            wrapper.eq(DistributionSchemeEntity::getDownstreamChannelId, queryDTO.getDownstreamChannelId());
        }
        
        if (StringUtils.hasText(queryDTO.getSchemeStatus())) {
            wrapper.eq(DistributionSchemeEntity::getSchemeStatus, queryDTO.getSchemeStatus());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge(DistributionSchemeEntity::getCreateTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le(DistributionSchemeEntity::getCreateTime, queryDTO.getEndTime());
        }
        
        wrapper.orderByDesc(DistributionSchemeEntity::getPriority)
                .orderByDesc(DistributionSchemeEntity::getCreateTime);
        
        IPage<DistributionSchemeEntity> result = distributionSchemeMapper.selectPage(page, wrapper);
        
        List<DistributionSchemeDTO> dtoList = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageResult<>(dtoList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public DistributionSchemeDTO getDistributionSchemeById(Long id) {
        DistributionSchemeEntity entity = distributionSchemeMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("分发方案不存在");
        }
        return convertToDTO(entity);
    }

    @Override
    public Long createDistributionScheme(DistributionSchemeDTO dto) {
        DistributionSchemeEntity entity = convertToEntity(dto);
        entity.setSchemeStatus("enabled");
        entity.setCreateBy(SecurityUtils.getCurrentUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setDeleted(0);
        
        distributionSchemeMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateDistributionScheme(Long id, DistributionSchemeDTO dto) {
        DistributionSchemeEntity existingEntity = distributionSchemeMapper.selectById(id);
        if (existingEntity == null) {
            throw new BusinessException("分发方案不存在");
        }
        
        DistributionSchemeEntity entity = convertToEntity(dto);
        entity.setId(id);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        
        distributionSchemeMapper.updateById(entity);
    }

    @Override
    public void deleteDistributionScheme(Long id) {
        DistributionSchemeEntity entity = distributionSchemeMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("分发方案不存在");
        }
        
        entity.setDeleted(1);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        distributionSchemeMapper.updateById(entity);
    }

    @Override
    public void batchDeleteDistributionScheme(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<DistributionSchemeEntity> entities = distributionSchemeMapper.selectBatchIds(ids);
            String currentUsername = SecurityUtils.getCurrentUsername();
            LocalDateTime now = LocalDateTime.now();
            
            for (DistributionSchemeEntity entity : entities) {
                entity.setDeleted(1);
                entity.setUpdateBy(currentUsername);
                entity.setUpdateTime(now);
                distributionSchemeMapper.updateById(entity);
            }
        }
    }

    @Override
    public void updateDistributionSchemeStatus(Long id, String status) {
        DistributionSchemeEntity entity = distributionSchemeMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("分发方案不存在");
        }
        
        entity.setSchemeStatus(status);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        distributionSchemeMapper.updateById(entity);
    }

    @Override
    public List<DistributionSchemeDTO> getEnabledDistributionSchemeList() {
        LambdaQueryWrapper<DistributionSchemeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DistributionSchemeEntity::getSchemeStatus, "enabled")
                .eq(DistributionSchemeEntity::getDeleted, 0)
                .orderByDesc(DistributionSchemeEntity::getPriority)
                .orderByDesc(DistributionSchemeEntity::getCreateTime);
        
        List<DistributionSchemeEntity> entities = distributionSchemeMapper.selectList(wrapper);
        return entities.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private DistributionSchemeDTO convertToDTO(DistributionSchemeEntity entity) {
        DistributionSchemeDTO dto = new DistributionSchemeDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private DistributionSchemeEntity convertToEntity(DistributionSchemeDTO dto) {
        DistributionSchemeEntity entity = new DistributionSchemeEntity();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}